import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
// import VueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from '@vant/auto-import-resolver';
import postCssPxToRem from "postcss-pxtorem";
import vueSetupExtend from "vite-plugin-vue-setup-extend";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

import fs from 'fs-extra'; // 用于删除文件夹
import archiver from 'archiver'; // 用于生成 ZIP 文件
import path from "path";
import { viteMockServe } from 'vite-plugin-mock'
import viteCompression from "vite-plugin-compression"; //生产环境 gzip 压缩资源
// 当前工作目录路径
const root = process.cwd();
// 打包时间
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
const timestamp = `${year}${month}${day}${hours}${minutes}${seconds}`;

export default defineConfig(({ mode }) => {
   const env = loadEnv(mode, root)
   const { VITE_BASE_URL, VITE_BASE_API } = env
   return {
      base: VITE_BASE_URL,
      define: {
         __appVersionTime__: timestamp,
      },
      build: {
         // chunkSizeWarningLimit: 1000,
         outDir: 'dist', // 指定输出目录
         minify: 'terser',
         terserOptions: {
            compress: {
               drop_console: true, // 去除console
               drop_debugger: true, // 去除debugger
               pure_funcs: ['console.log', 'console.info', 'console.warn', 'console.error', 'console.debug'], // 去除指定的console函数
            },
            format: {
               comments: false // 移除所有注释
            }
         },
         rollupOptions: {
            output: {
               // 自定义打包输出的文件夹结构
               chunkFileNames: 'js/[name]-[hash].js', // 动态导入的 JS
               entryFileNames: 'js/[name]-[hash].js', // 主入口 JS
               assetFileNames: (assetInfo) => {
                  // 根据资源类型分文件夹
                  const extType = path.extname(assetInfo.name).slice(1); // 获取文件扩展名
                  if (extType === 'css') {
                     return 'css/[name]-[hash][extname]'; // CSS 文件
                  } else if (['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'].includes(extType)) {
                     return 'img/[name]-[hash][extname]'; // 图片文件
                  }
                  return 'assets/[name]-[hash][extname]'; // 其他资源
               }
            },
         }
      },
      server: {
         port: 3631,
         host: '0.0.0.0',
         open: true,
         proxy: {
            [VITE_BASE_API]: {
               // target: 'http://192.168.1.33:8082',//熊上
               // target: 'http://192.168.50.99:8081',//石秀
               // target: 'http://192.168.50.139:8080',// 刘康
               target: 'http://192.168.50.11:8080',
               changeOrigin: true,
               // rewrite: (p) => p.replace(/^\/dev-api/, '')
               rewrite: (path) => path.replace(new RegExp(`^${VITE_BASE_API}`), '')
            }
         }
      },
      plugins: [
         vue(
            {
               template: {
                  compilerOptions: {
                     comments: false
                  }
               }
            }
         ),
         {
            name: 'remove-html-comments',
            transformIndexHtml(html) {
              return html.replace(/<!--[\s\S]*?-->/g, '') // 移除所有 HTML 注释
            }
         },
         // VueDevTools(),// 官方调试工具
         viteMockServe({
            mockPath: './mock/', // 设置模拟数据的存储文件夹
            supportTs: false, // 是否读取ts文件模块
            logger: true, //  是否在控制台显示请求日志
            localEnabled: true, //设置是否启用本地mock文件
            prodEnabled: false //设置打包是否启用 mock 功能
         }),
         // svg 图标
         createSvgIconsPlugin({
            // 指定图标文件夹
            iconDirs: [path.resolve(root, "src/assets/icons/svg")],
            symbolId: "icon-[dir]-[name]"
         }),
         // 允许 setup 语法糖上添加组件名属性
         vueSetupExtend(),
         // 生产环境 gzip 压缩资源
         viteCompression(),
         // 自动导入
         AutoImport({
            resolvers: [VantResolver()],
            imports: [
               'vue',
               'vue-i18n',
               'vue-router',
               {
                  '@vueuse/core': [
                     'useMouse', // import { useMouse } from '@vueuse/core',
                     ['useFetch', 'useMyFetch'], // import { useFetch as useMyFetch } from '@vueuse/core',
                  ],
                  'axios': [
                     // default imports
                     ['default', 'axios'], // import { default as axios } from 'axios',
                  ],
                  '[package-name]': [
                     '[import-names]',
                     ['[from]', '[alias]'],
                  ],
               }
            ],
            dirs: [
               'src/composables',
               'src/store/modules',
            ],
            vueTemplate: true,
         }),
         Components({
            resolvers: [VantResolver()],
         }),
         {
            name: 'build-zip-plugin',
            apply: 'build',
            async buildStart() {
               const distPath = path.resolve(__dirname, 'dist');
               if (fs.existsSync(distPath)) {
                  console.log('清理 dist 文件夹...');
                  await fs.remove(distPath);
               }
            },
            async closeBundle() {
               const distPath = path.resolve(__dirname, 'dist');
               const zipName = `h5_dist_${timestamp}.zip`;
               const zipPath = path.resolve(__dirname, zipName);
               console.log(`正在创建 ZIP 文件: ${zipName}...`);
               const output = fs.createWriteStream(zipPath);
               const archive = archiver('zip', { zlib: { level: 9 } });
               archive.pipe(output);
               archive.directory(distPath, false);
               await archive.finalize();
               console.log(`ZIP 文件已生成: ${zipPath}`);
            },
         },
      ],
      css: {
         postcss: {
            preprocessorOptions: {
               scss: {
                  api: 'modern-compiler',
                  silenceDeprecations: ['legacy-js-api']
               }
            },
            plugins: [
               postCssPxToRem({
                  rootValue: 75, // 1rem，根据 设计稿宽度/10 进行设置
                  propList: ['*'], // 需要转换的属性，这里选择全部都进行转换
                  selectorBlackList: ["norem"], // 过滤掉norem-开头的class，不进行rem转换
                  exclude: '.no-rem'
               })
            ]
         }
      },
      resolve: {
         alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
         }
      }
   }
}
)
